package com.lack.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lack.openApicommon.model.entity.InterfaceInfo;
import com.lack.openApicommon.model.entity.UserInterfaceInfo;
import com.lack.project.annotation.AuthCheck;
import com.lack.project.common.BaseResponse;
import com.lack.project.common.ErrorCode;
import com.lack.project.common.ResultUtils;
import com.lack.project.exception.BusinessException;
import com.lack.project.mapper.UserInterfaceInfoMapper;
import com.lack.project.model.vo.InterFaceInfoVO;
import com.lack.project.service.InterfaceInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 热门接口
 */
@RestController
@RequestMapping("/top")
public class TopController {
    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @GetMapping("/interface")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<InterFaceInfoVO>> getTop() {
        // 获取前3个调用量最多的接口
        List<UserInterfaceInfo> userInterfaceInfos = userInterfaceInfoMapper.getTop(3);
        // 将UserInterfaceInfo对象转换为Map，键为接口ID，值为对应的UserInterfaceInfo对象列表
        Map<Long, List<UserInterfaceInfo>> listMap = userInterfaceInfos.stream().collect(Collectors.groupingBy(UserInterfaceInfo::getInterFaceInfoId));
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        // 筛选出接口ID在listMap中的接口
        queryWrapper.in("id", listMap.keySet());
        List<InterfaceInfo> list = interfaceInfoService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据库中无数据");
        }
        // 将列表中的每个InterFaceInfo对象转换为InterFaceInfoVO对象，并设置其totalNum属性
        List<InterFaceInfoVO> collect = list.stream().map(interfaceinfo -> {
            // 创建一个InterFaceInfoVO对象，用于存储转换后的属性
            InterFaceInfoVO interFaceInfoVO = new InterFaceInfoVO();
            // 将InterFaceInfo对象的属性复制到InterFaceInfoVO对象
            BeanUtils.copyProperties(interfaceinfo, interFaceInfoVO);
            // 获取与InterFaceInfo对象ID对应的totalNum属性值
            Integer totalNum = listMap.get(interfaceinfo.getId()).get(0).getTotalNum();
            // 设置InterFaceInfoVO对象的totalNum属性
            interFaceInfoVO.setTotalNum(totalNum);
            // 返回转换后的InterFaceInfoVO对象
            return interFaceInfoVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }
}
